package com.网络编程.net.http;

import com.alibaba.fastjson.JSON;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * 往一个接口发送post请求和json格式的数据
 * @author liyiruo
 * @Description
 * @Date 2023/3/15 下午3:11
 */
public class HttpClientPostJson{
    public static void main(String[] args) {
        String url = "http://localhost:9008/lyr/my/getData";
        //数据格式
        /*
                        {
                    "reqcontent": {
                        "txCode": "PM_GH_001",
                        "date": "202302",
                        "sendDate": "20230218"
                    }
                }
         */
        Map paramMap = new HashMap<String, Object>(16);
        Map reqcontent = new HashMap<String, Object>(16);
        paramMap.put("txCode","PM_GH_001");
        paramMap.put("date","202302");
        paramMap.put("sendDate","20230218");
        reqcontent.put("reqcontent", paramMap);

        String s = postRequest(url, reqcontent);
        System.out.println(s);
    }

    public static String postRequest(String url, Map<String, Object> paramMap) {
        Object o = JSON.toJSON(paramMap);
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // 创建httpPost远程连接实例
        HttpPost post = new HttpPost(url);
        String result = "";
        try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) {
            // 修复 POST json 导致中文乱码
            HttpEntity entity = new StringEntity(o.toString(), "UTF-8");
            post.setEntity(entity);
            post.setHeader("Content-type", "application/json");
            HttpResponse resp = closeableHttpClient.execute(post);
            try {
                InputStream respIs = resp.getEntity().getContent();
                byte[] respBytes = IOUtils.toByteArray(respIs);
                result = new String(respBytes, Charset.forName("UTF-8"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
